﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;
using ERP_SaaS_WinForm.销售.Sales;

namespace ERP_SaaS_WinForm.销售
{
    public partial class Client : Form
    {
        private List<SaleClinentDTO> clientList = new List<SaleClinentDTO>();

        public SaleClinentDTO SelectedClient { get; private set; }

        public Client()
        {
            InitializeComponent();
            this.StartPosition = FormStartPosition.CenterParent;
            this.Text = "选择客户";
            this.Load += Client_Load;
        }

        private async void Client_Load(object sender, EventArgs e)
        {
            await LoadClientDataAsync(null);
        }

        private async Task LoadClientDataAsync(string clientName)
        {
            try
            {
                string baseUrl = "http://localhost:5054/api/Client/GetClient";
                var queryParams = new List<string>();
                if (!string.IsNullOrWhiteSpace(clientName)) queryParams.Add($"clientName={clientName.Trim()}");
                string url = queryParams.Count > 0 ? $"{baseUrl}?{string.Join("&", queryParams)}" : baseUrl;

                using (HttpClient http = new HttpClient())
                {
                    HttpResponseMessage response = await http.GetAsync(url);
                    response.EnsureSuccessStatusCode();
                    string json = await response.Content.ReadAsStringAsync();
                    SaleApiResponse api = JsonConvert.DeserializeObject<SaleApiResponse>(json);
                    if (api.code == 200)
                    {
                        clientList = api.data ?? new List<SaleClinentDTO>();
                        dgvClients.DataSource = clientList;
                    }
                    else
                    {
                        MessageBox.Show($"查询失败: {api.msg}");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取客户数据失败: {ex.Message}");
            }
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            await LoadClientDataAsync(txtSearchName.Text);
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            if (dgvClients.CurrentRow == null)
            {
                MessageBox.Show("请先选择一条客户记录");
                return;
            }

            SelectedClient = dgvClients.CurrentRow.DataBoundItem as SaleClinentDTO;
            if (SelectedClient == null)
            {
                MessageBox.Show("无法获取所选客户信息");
                return;
            }
            this.DialogResult = DialogResult.OK;
            this.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void dgvClients_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                btnOk_Click(sender, EventArgs.Empty);
            }
        }
    }
}
